package com.danbai.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.danbai.reggie.common.R;
import com.danbai.reggie.entity.User;
import com.danbai.reggie.service.UserService;
import com.danbai.reggie.utils.SMSUtils;
import com.danbai.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //获取手机号
        String phone = user.getPhone();

        if(StringUtils.isNotEmpty(phone)){
            //随机4位的验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("验证码:{}",code);
            //发送短信
//            SMSUtils.sendMessage("阿里云短信测试","",phone,code);
            //将验证码存到session域中
            session.setAttribute(phone,code);

            return R.success("手机验证码短信发送成功");
        }
        return R.error("短信发送失败");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map map,HttpSession session){
        //获取手机号
        String phone =(String)map.get("phone");
        //获取验证码
        String code = (String)map.get("code");
        //从session中获取验证码
        String codeInSession =(String)session.getAttribute(phone);
        //进行验证码的比对
        if (codeInSession != null && codeInSession.equals(code)){
            //如果能对比成功,说明登录成功

            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);

            User user = userService.getOne(queryWrapper);

            if (user == null){
                //判断当前手机是否为新用户,如果是新用户则自动完成注册
                User user1 = new User();
                user1.setPhone(phone);
                userService.save(user1);
                session.setAttribute("user",user1.getId());
            }else {
                session.setAttribute("user",user.getId());
            }
            return R.success(user);
        }
        //登录失败
        return R.error("登录失败");
    }
}
